/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package utain.quiz1;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *
 * @author Nut
 */
public class UtainXMLParser extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        String url = request.getParameter("url");
        String ename = request.getParameter("ename").toLowerCase();
        String key = request.getParameter("key").toLowerCase();
        if (url.trim().isEmpty() || ename.trim().isEmpty()) {
            PrintWriter pw = response.getWriter();
            pw.print("<script>"
                    + "alert('Plear enter URL and Element name');"
                    + "window.location='http://localhost:8080/Utain-quiz1-2013/'"
                    + "</script>");
        } else {
            try {
                String[] mapInput = {url, ename, key};
                processingXML(response, mapInput);
            } catch (Exception ex) {
                Logger.getLogger(UtainXMLParser.class.getName()).log(Level.SEVERE, null, ex);
            }
            // }

        }
    }

    protected void processingXML(HttpServletResponse response, String[] arg) throws Exception {
        PrintWriter out = response.getWriter();
        out.print("<html><body><table align='center' border='1' ><tr><th> Title </th><th> Price </th></tr>");

        try {
            URL url = new URL(arg[0].toString());
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(url.openStream());
            // Read the entire cocument in to memory

            NodeList books = doc.getElementsByTagName("book");
            for (int i = 0; i < books.getLength(); i++) {
                Element bookItem = (Element) books.item(i);

                String tiT = getEleVal(bookItem, "title");
                Double priCT = Double.parseDouble(getEleVal(bookItem, "price"));
                if (arg[1].equalsIgnoreCase("title")) {
                    if (tiT.toLowerCase().contains(arg[2])) {
                        out.print("<tr><td>" + tiT + "</td><td>" + priCT + "</td></tr>");
                    } else {
                        out.print("<script>"
                                + "window.location='http://localhost:8080/Utain-quiz1-2013/';"
                                + "alert('" + arg[2] + " not found in element " + arg[1] + " \nfrom url: " + arg[0] + "');"
                                + "</script>");
                    }
                } else if (arg[1].equalsIgnoreCase("price")) {
                    if (priCT >= Double.parseDouble(arg[2])) {
                        out.print("<tr><td>" + tiT + "</td><td>" + priCT + "</td></tr>");
                    }
                } else {
                    out.print("<script>"
                            + "window.location='http://localhost:8080/Utain-quiz1-2013/';"
                            + "alert('Element name not found');"
                            + "</script>");
                }
            }

            out.print("</table></body></html>");
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            out.close();
        }

    }

    protected String getEleVal(Element parent, String label) {
        Element e = (Element) parent.getElementsByTagName(label).item(0);
        try {
            Node child = e.getFirstChild();
            if (child instanceof CharacterData) {
                CharacterData cd = (CharacterData) child;
                return cd.getData();
            }
        } catch (Exception ex) {

        }
        return "";
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
